package service

import (
	"buding-ai/internal/repository"
	"buding-ai/internal/repository/model"
	"buding-ai/internal/web/dto"
	"buding-ai/internal/web/response"
	"buding-ai/pkg/utils/paginate"

	"errors"
	"github.com/jinzhu/copier"
	"sync"
)

type AgentRoleService struct {
	agentRoleRepository *repository.AgentRoleRepository
}

var (
	agentRoleSrv  *AgentRoleService
	agentRoleOnce sync.Once
)

func NewAgentRoleService() *AgentRoleService {
	agentRoleOnce.Do(func() {
		agentRoleSrv = &AgentRoleService{
			agentRoleRepository: repository.GetAgentRoleRepository(),
		}
	})
	return agentRoleSrv
}

func (srv *AgentRoleService) Create(dto dto.AgentRoleDTO) error {
	exists, err := srv.agentRoleRepository.CheckAgentRoleExistsByName(dto.Name)
	if err != nil {
		return errors.New("查询数据库失败" + err.Error())
	}
	if exists {
		return errors.New("条目已存在")
	}
	//先关闭所有的相同type的
	if dto.Status == 1 {
		if err := srv.agentRoleRepository.CloseByType(dto.Type); err != nil {
			return errors.New("禁用条目失败:" + err.Error())
		}
	}
	//插入数据
	var agentROle model.AgentRole
	copier.Copy(&agentROle, &dto)
	if err := srv.agentRoleRepository.Create(agentROle); err != nil {
		return errors.New("插入失败:" + err.Error())
	}
	return nil
}

func (srv *AgentRoleService) GetById(id uint) (*response.AgentRoleInfoVO, error) {
	var agentRole *model.AgentRole
	var err error
	agentRole, err = srv.agentRoleRepository.GetById(id)
	if err != nil {
		return nil, err
	}
	var resp response.AgentRoleInfoVO
	copier.Copy(&resp, agentRole)

	return &resp, nil
}

func (srv *AgentRoleService) DeleteById(id uint) error {
	return srv.agentRoleRepository.DeleteById(id)
}

func (srv *AgentRoleService) Update(agentDTO dto.AgentRoleDTO) error {
	agentRole, err := srv.agentRoleRepository.GetById(agentDTO.ID)
	if err != nil {
		return err
	}
	if agentRole.ID == 0 {
		return errors.New("条目不存在")
	}
	copier.Copy(&agentRole, agentDTO)
	if err := srv.agentRoleRepository.Update(agentRole); err != nil {
		return err
	}
	return nil
}

func (srv *AgentRoleService) GetPage(request paginate.PageRequest) (*paginate.PageResponse, error) {
	pageResult, err := srv.agentRoleRepository.GetPage(request)
	if err != nil {
		return nil, ErrDatabaseError
	}
	return pageResult, nil
}

func (srv *AgentRoleService) List() ([]model.AgentRole, error) {
	roles, err := srv.agentRoleRepository.List()
	if err != nil {
		return nil, ErrDatabaseError
	}
	return roles, nil
}
